import {
    validate,
    IsInt,
    IsString,
} from 'class-validator';
import {plainToInstance} from 'class-transformer'
import 'reflect-metadata'

export class CreateUserDto {
    @IsInt()
    age: number;

    @IsString()
    name: string;
}

let user = new CreateUserDto();
user.name = "小明";
(user as any).age = '18';

validate(user).then(errors=>{
    if(errors.length){
        console.log('校验失败')
        console.log(errors);
    // [
    //         ValidationError {
    //              target: CreateUserDto { name: '小明', age: '18' },
    //              value: '18',
    //              property: 'age',
    //              children: [],
    //              constraints: { isInt: 'age must be an integer number' }
    //          }
    // ]
    }else{
        console.log('校验成功')
    }
})

// 为什么要用class-transformer库转化
// 客户端请求接口拿到的数据是普通函数不是类的实例
// 要检验先转为类的实例对象

const apiUser = {
    age:18,
    name:'小明'
}
validate(plainToInstance(CreateUserDto,apiUser)).then(errors=>{
    if(errors.length){
        console.log('普通对象转类实例对象校验，失败的')
    }else{
        console.log('普通对象转类实例对象校验，成功的')
    }
})
